package com.imc.platform.base.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.imc.core.utils.MysqlUtil;
import com.imc.platform.base.banner.pojo.BannerItem;
import com.imc.platform.base.common.pojo.TypePic;
import com.imc.platform.base.common.service.ICommonPicService;
import com.twp.common.tuple.ResultDTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/*
 * 类描述：图片通用处理类
 * 开发者：YT
 * 创建日期：2018/9/14 13:39
 */
@Slf4j
@Controller
@RequestMapping("/common")
public class CommonController {

    public static final String imgUrl = "/images/";

    @Autowired
    ICommonPicService commonPicService;

    @Value("${img.location}")
    String location;

    @Value("${img.accessPath}")
    String accessPath;

    @Autowired
    MysqlUtil mysqlUtil;

    /**
     * QY 2018/9/3 8:01
     * 方法描述：传参对象
     **/
    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class ReqTuple {
        Map <String, String> parmsMap;
    }

    /**
     * QY 2018/10/08 23:49
     * 方法描述：跳转上传图片页面
     **/
    @RequestMapping(value = "/toUploadPage", method = RequestMethod.GET)
    public String toUploadPage(@RequestParam String bnId, @RequestParam String table_name, @RequestParam String column_name, @RequestParam String dataSize, @RequestParam String dataHeight, @RequestParam String dataWidth, @RequestParam String typeDir, @RequestParam String dataNum, @RequestParam String operatorAdd, @RequestParam String operatorDel,@RequestParam String column_nametwo,@RequestParam String column_nameone, Model model) {
        Map <String, Object> map = new HashMap <>();
        model.addAttribute("bnId", bnId); //主键ID
        model.addAttribute("table_name", table_name);//上传图片对应的表名
        model.addAttribute("column_name", column_name);//上传图片对应的字段名称。每个表可能不一致
        model.addAttribute("column_nametwo", column_nametwo);//图片存储目录
        model.addAttribute("column_nameone", column_nameone);//图片存储目录
        model.addAttribute("dataSize", dataSize);//图片大小
        model.addAttribute("dataWidth", dataWidth);//图片宽度
        model.addAttribute("dataHeight", dataHeight);//图片高度
        model.addAttribute("dataNum", dataNum);//图片高度
        model.addAttribute("typeDir", typeDir);//图片存储目录
        model.addAttribute("operatorAdd", operatorAdd);//图片存储目录
        model.addAttribute("operatorDel", operatorDel);//图片存储目录

        //上传图片页面
        return "base/common/uploadHtml";
    }

    /*
     * YT  2018/11/24 16:55
     * 方法描述：跳转到预览图片页面
     */
    @RequestMapping(value = "/toYuLan", method = RequestMethod.GET)
    public String toYuLan(@RequestParam String url, String width, String height, Model model) {
        Map <String, Object> map = new HashMap <>();
        model.addAttribute("url", url);
        model.addAttribute("width", width);
        model.addAttribute("height", height);
        return "base/common/yuLanHtml";
    }

    /**
     * QY 2018/9/3 10:16
     * 方法描述：查询所有类型的图片
     **/
    @RequestMapping(value = "/queryTypePics", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO queryTypePics(Principal principal, @RequestBody ReqTuple reqTuple) {
        PageInfo <TypePic> queryList = commonPicService.queryTypePicByMap(Integer.parseInt(reqTuple.getParmsMap().get("page")), Integer.parseInt(reqTuple.getParmsMap().get("size")), reqTuple.getParmsMap());
        JSONObject map = new JSONObject();
        map.put("total", queryList.getTotal());
        map.put("rows", queryList.getList());
        ResultDTO result = ResultDTO.builder().data(map).build();
        return result;
    }

    /*
     * YT  2018/11/24 16:56
     * 方法描述：预览图片
     */
    @RequestMapping("/lookUrl")
    @ResponseBody
    public ResultDTO lookUrl(String column, String biId, String imgName, String table_name,String columnone,String columntwo) throws Exception {
        String lookUrl = commonPicService.lookUrl(column, biId, imgName, table_name,columnone,columntwo);
        JSONObject map = new JSONObject();
        map.put("url", lookUrl);
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /*
     * YT  2018/11/24 17:19
     * 方法描述：上传图片
     */
    @RequestMapping("/uploadPic")
    @ResponseBody
    public ResultDTO uploadPic(@RequestParam("file") MultipartFile file, String bnId, String typeDir, HttpServletRequest request) throws Exception {
        JSONObject map = new JSONObject();
        //图片模块上传多图片时候，只新增附件表。
        if (null != bnId && !"".equals(bnId)) {
            String realPath = path(request, typeDir);
            String savePath = savePath(request, typeDir);
            String fileName = upImg(savePath, file);
            if (null != fileName && !"".equals(fileName)) {
                map.put("reCode", "4001");
                map.put("bnId", bnId);
                map.put("imgName", fileName);
                map.put("imgUrl", realPath + fileName);
            } else {
                //图片上传失败
                map.put("reCode", "4002");
            }
        }
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:图片上传 返回图片路径
     * SJC 2018-8-26 16:03:21
     */
    private String upImg(String savePath, MultipartFile file) {

        String relFn = null;
        try {
            if (null != file) {
                String filename = URLEncoder.encode(file.getOriginalFilename(), "utf-8");
                File filepath = new File(savePath, filename);
                //判断路径是否存在，如果不存在就创建一个
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();
                }

                InputStream inputStream = file.getInputStream();
                FileOutputStream fileOutputStream = null;
                String fnName = makeFileName(filename);
                relFn = fnName;
                byte[] data = new byte[1024];
                int len = 0;
                fileOutputStream = new FileOutputStream(savePath + fnName);
                while ((len = inputStream.read(data)) != -1) {
                    fileOutputStream.write(data, 0, len);
                }
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return relFn;
    }

    /*
     * YT  2018/11/24 17:23
     * 方法描述：为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
     */
    private static String makeFileName(String filename) { //2.jpg
        return UUID.randomUUID().toString() + "_" + filename;
    }

    /*
     * YT  2018/11/24 17:26
     * 方法描述：绝对路径
     */
    public String path(HttpServletRequest request, String typeDir) {
        //开发用：
//        String indeStr = "http://" + request.getServerName() // 服务器地址
//                + ":" + request.getServerPort() // 端口号
//                + request.getContextPath(); // 项目名称
//        //现网：
//        /*String indeStr = "https://" + request.getServerName() // 服务器地址
//                + request.getContextPath(); // 项目名称*/
        return accessPath + imgUrl + typeDir + "/";
    }

    /*
     * YT  2018/11/24 17:26
     * 方法描述：相对路径
     */
    public String savePath(HttpServletRequest request, String typeDir) {
        //String savePath = request.getSession().getServletContext().getRealPath(imgUrl + typeDir +"/");
        return location + imgUrl + typeDir + "/";
    }
}